package com.thinksns.sociax.t4.android.map;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.thinksns.sociax.android.R;
import com.thinksns.sociax.t4.adapter.PoiAdapter;
import com.thinksns.sociax.t4.android.ThinksnsAbscractActivity;
import com.thinksns.sociax.t4.unit.DeviceUtils;
import com.thinksns.tschat.constant.TSConfig;
import com.thinksns.tschat.widget.SmallDialog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 用于发布动态选择地理位置
 * 用于聊天发送地理信息
 * 传入参数
 * from_chat 是否来自聊天发送定位,默认为 false
 */
public class ActivityGetMyLocation extends ThinksnsAbscractActivity
        implements LocationSource, AMapLocationListener, PoiSearch.OnPoiSearchListener, AMap.OnMapClickListener, AMap.OnMapScreenShotListener, AMap.OnMapLoadedListener {

    public static final float MAP_ZOOM_LEVEL = 16.1f;// 地图缩放级别
    public static final boolean FROM_CHAT_MORE = true; // 来自聊天发送定位

    private TextView mTvTitle;
    private ImageButton tv_title_left;
    private TextView tvCancel;
    private EditText etSearch;
    private ListView listPoi;
    private View headerView;
    private TextView headerStreet;
    private MapView mapView;

    private SmallDialog dialog;
    private PoiAdapter adapter;
    // 地图相关
    private AMap aMap;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    // about map data 定位获取当前位置
    private String currentAddress;
    private double currentLatitude, currentLongitude;
    // Poi
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;
    private PoiResult poiResult; // poi返回的结果
    private List<PoiItem> poiItems;// poi数据

    private LatLonPoint locationPoint;//定位点
    private String strCity;
    private Marker mSingleMarker; // 点击地图添加一个标记（最多一个）
    private boolean isFromChatMore; // 是否来自聊天
    // 选择的地理位置信息
    private String mSelectAddress;
    private double mSelectLatitude;
    private double mSelectLongitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreateNoTitle(savedInstanceState);
        initIntent();
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 必须要写
        initView();
        initMap();
    }

    protected void initIntent() {
        isFromChatMore = getIntent().getBooleanExtra("from_chat", !FROM_CHAT_MORE);
    }

    /**
     * 初始化地图相关
     */
    private void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            aMap.setLocationSource(this);// 设置定位监听
            aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
            // aMap.setMyLocationStyle(AMap.MAP_TYPE_NORMAL);
            aMap.setMyLocationStyle(new MyLocationStyle());
            aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
            aMap.setOnMapClickListener(this); // 地图点击事件
            aMap.setOnMapLoadedListener(this); // 地图加载完成回调
            // aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);（该方法为老版本的方法，现在不能用了）
        }
    }

    /**
     * 初始化控件
     */
    private void initView() {
        tv_title_left = (ImageButton) findViewById(R.id.tv_title_left);
        mTvTitle = (TextView) findViewById(R.id.tv_title_center);
        listPoi = (ListView) findViewById(R.id.list_poi);
        etSearch = (EditText) findViewById(R.id.et_address_search);
        tvCancel = (TextView) findViewById(R.id.tv_cancel);
        headerView = getLayoutInflater().inflate(R.layout.header_my_location, null, false);
        headerStreet = (TextView) headerView.findViewById(R.id.tv_location_street);
        if (isFromChatMore){
            mTvTitle.setText(R.string.location_share);
        }else{
            mTvTitle.setText(R.string.location_here);
        }
        initListener();
    }

    /**
     * 初始化监听事件
     */
    private void initListener() {
        tv_title_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityGetMyLocation.this.finish();
            }
        });

        headerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                v.setEnabled(false);
                mSelectAddress = currentAddress;
                mSelectLatitude = currentLatitude;
                mSelectLongitude = currentLongitude;
                if (isFromChatMore) {
                    aMap.getMapScreenShot(ActivityGetMyLocation.this);
                } else {
                    returnLocation(currentAddress, currentLatitude, currentLongitude, null);
                }
            }
        });
        /**
         * 搜索输入框焦点事件
         */
        etSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvCancel.setVisibility(View.VISIBLE);
            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                switch (actionId) {
                    case EditorInfo.IME_ACTION_SEARCH:
                        doSearch();
                        DeviceUtils.hideSoftKeyboard(getApplicationContext(), v);
                        break;
                }

                return true;
            }
        });
        /**
         * 取消搜索
         */
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvCancel.setVisibility(View.GONE);
                DeviceUtils.hideSoftKeyboard(getApplicationContext(), v);
            }
        });

        listPoi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (id >= 0) {
                    PoiItem poiItem = adapter.getItem((int) id);
                    mSelectAddress = poiItem.getTitle();
                    mSelectLatitude = poiItem.getLatLonPoint().getLatitude();
                    mSelectLongitude = poiItem.getLatLonPoint().getLongitude();
                    if (isFromChatMore) {
                        aMap.getMapScreenShot(ActivityGetMyLocation.this);
                    } else {
                        returnLocation(mSelectAddress, mSelectLatitude, mSelectLongitude, null);
                    }
                }
            }
        });
    }

    /***
     * 响应搜索操作
     */
    private void doSearch() {
        String keyWords = etSearch.getText().toString();
        if (TextUtils.isEmpty(keyWords)) {
            Toast.makeText(ActivityGetMyLocation.this, "请输入要搜索内容", Toast.LENGTH_SHORT).show();
            return;
        }
        if (locationPoint == null || strCity == null) {
            Toast.makeText(ActivityGetMyLocation.this, "获取定位信息失败", Toast.LENGTH_SHORT).show();
            return;
        }
        doSearchQuery(keyWords, strCity, locationPoint);
    }

    /**
     * 显示提示框
     */
    private void showDialog() {
        showDialog("请稍后...");
    }

    /**
     * 显示提示框
     *
     * @param msg 消息
     */
    private void showDialog(String msg) {
        if (dialog == null) {
            dialog = new SmallDialog(this, msg);
        } else {
            dialog.setContent(msg);
        }
        dialog.show();
    }

    /**
     * 隐藏提示框
     */
    private void hideDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
//        mapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public String getTitleCenter() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_get_my_location;
    }

    /**
     * 地图加载完成
     */
    @Override
    public void onMapLoaded() {
        CameraUpdateFactory.zoomTo(MAP_ZOOM_LEVEL);
    }

    /**
     * 当定位发生变化
     *
     * @param amapLocation
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                CameraUpdateFactory.zoomTo(MAP_ZOOM_LEVEL);
                // 获取地理位置信息
                currentAddress = /*amapLocation.getProvince() + */amapLocation.getCity() + amapLocation.getDistrict() + amapLocation.getRoad();
                currentLatitude = amapLocation.getLatitude();
                currentLongitude = amapLocation.getLongitude();
                initPoiAround(amapLocation);
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
                Toast.makeText(this, "定位失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void returnLocation(String address, double latitude, double longitude, String path) {
        showDialog();
        Intent intent = getIntent();
        intent.putExtra("address", address);
        intent.putExtra("latitude", latitude);
        intent.putExtra("longitude", longitude);
        if (isFromChatMore) {
            intent.putExtra("path", path);
        }
        setResult(RESULT_OK, intent);
        ActivityGetMyLocation.this.finish();
    }

    /**
     * 初始化POI搜索
     *
     * @param amapLocation
     */
    private void initPoiAround(AMapLocation amapLocation) {
        String location = amapLocation.getProvince() + amapLocation.getCity() + amapLocation.getDistrict() + amapLocation.getRoad();
        headerStreet.setText(location);
//        listPoi.addHeaderView(headerView);
        strCity = amapLocation.getCity();
        locationPoint = new LatLonPoint(amapLocation.getLatitude(), amapLocation.getLongitude());
        doSearchQuery("", strCity, locationPoint);
    }

    /**
     * 进行poi查询
     *
     * @param lp
     */
    private void doSearchQuery(String keyWorlds, String city, LatLonPoint lp) {
        query = new PoiSearch.Query(keyWorlds, "", city);
        query.setPageSize(10);
        query.setPageNum(0);

        poiSearch = new PoiSearch(this, query);
        // 设置搜索区域为以lp点为圆心，其周围2000米范围
        poiSearch.setBound(new PoiSearch.SearchBound(lp, 2000, true));
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();  // 异步搜索
        showDialog();
    }

    /**
     * 激活定位
     *
     * @param listener
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置需要地理位置信息
            mLocationOption.isNeedAddress();
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            mLocationOption.setOnceLocation(true);
            mlocationClient.startLocation();
        }
    }

    /**
     * 取消定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        // 1000为成功，其他为失败,老版本的为0
        hideDialog();
        if (rCode == 1000) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    // 取得第一页的poiitem数据，页数从数字0开始
                    poiItems = poiResult.getPois();
                    if (poiItems != null && poiItems.size() > 0) {
                        Log.e("sn_", poiItems.toString());
                        adapter = new PoiAdapter(this, poiItems);
                        listPoi.removeHeaderView(headerView);
                        listPoi.setAdapter(adapter);
                        listPoi.addHeaderView(headerView);
                    }
                }
            }
        } else {
            Toast.makeText(ActivityGetMyLocation.this, "没有搜到到相关内容", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void onMapClick(LatLng latLng) {
        if (latLng != null) {
            addMarkersToMap(latLng);
            doSearchQuery("", "", new LatLonPoint(latLng.latitude, latLng.longitude));
        }
    }

    /**
     * 添加标记
     * @param latLng 标记对应的经纬度
     */
    private void addMarkersToMap(LatLng latLng) {
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
        //设置marker
        if (mSingleMarker == null) {
            MarkerOptions options = new MarkerOptions();
            options.icon(BitmapDescriptorFactory.fromResource(com.thinksns.tschat.R.drawable.redpin));
            options.draggable(false);
            options.position(latLng);
            mSingleMarker = aMap.addMarker(options);
        } else {
            mSingleMarker.remove();
            mSingleMarker = null;
            addMarkersToMap(latLng);

        }
    }

    /**
     * 截图当前地图回调
     * @param bitmap
     */
    @Override
    public void onMapScreenShot(Bitmap bitmap) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        if (null == bitmap) {
            dialog.setContent("获取位置截图数据失败");
            dialog.show();
        } else {
            String error = "";
            try {
                String path = Environment.getExternalStorageDirectory() + "/" + TSConfig.CACHE_PATH;
                File file = new File(path);
                if (!file.exists()) {
                    //创建目录
                    file.mkdirs();
                }

                path = path + "/location_" + sdf.format(new Date()) + ".png";
                FileOutputStream fos = new FileOutputStream(path);
                boolean b = bitmap.compress(Bitmap.CompressFormat.PNG, 80, fos);
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (b) {
                    //发送位置
                    returnLocation(mSelectAddress, mSelectLatitude, mSelectLongitude, path);
                    return;
                } else {
                    error = "获取位置信息失败,请重新定位";
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                error = "保存位置文件路径错误";
            } finally {
                dialog.setContent(error);
                dialog.show();
            }
        }
    }
}

